package com.likersai.opon.pojo.bo;

import com.likersai.opon.constant.MsgAndCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.ArrayList;
import java.util.List;

import static com.likersai.opon.constant.ResponseMsg.FAILURE_PARAM_VALID;
import static com.likersai.opon.constant.ResponseMsg.SUCCESS;

/**
 * 请求接口返回模型
 *
 * @author sun.ye
 * @since 2021-01-13 23:28
 */
@Data
@ApiModel(value = "接口请求返回模型",description = "统一的接口请求返回封装")
public class ResponseBO<T> {

    @ApiModelProperty(value = "响应编码",name = "param code",notes = "notes")
    private String code;
    @ApiModelProperty(value = "响应编码名称",name = "param name",notes = "notes")
    private String name;
    @ApiModelProperty(value = "响应信息",name = "param message",notes = "notes")
    private String message;
    @ApiModelProperty(value = "响应数据",name = "param message",notes = "notes")
    private T data;

    private ResponseBO (MsgAndCode msgAndCode) {
        this.code = msgAndCode.getCode();
        this.name = msgAndCode.getName();
        this.message = msgAndCode.getMessage();
    }

    public static <T> ResponseBO<T> getSuccess(T data) {
        ResponseBO<T> responseModel =  new ResponseBO<>(SUCCESS);
        responseModel.setData(data);
        return responseModel;
    }

    public static <T> ResponseBO<T> getException(MsgAndCode exceptionMsg) {
        return new ResponseBO<>(exceptionMsg);
    }
    
    public static <T> ResponseBO<T> getException(MsgAndCode exceptionMsg,T data) {
        ResponseBO<T> responseBO = new ResponseBO<>(exceptionMsg);
        responseBO.setData(data);
        return responseBO;
    }

    public static ResponseBO<List<String>> getFailureValid(BindingResult bindingResult) {

        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        List<String> errerMessage = new ArrayList<>();
        for (FieldError error : fieldErrors) {
            errerMessage.add(error.getDefaultMessage());
        }

        ResponseBO<List<String>> responseModel =  new ResponseBO<>(FAILURE_PARAM_VALID);
        responseModel.setData(errerMessage);
        return responseModel;
    }

}